package com.sto.stoapp.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.sto.stoapp.dataprocess.ProcessUploadData;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.http.MessageType;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.server.StoDownServer;
import com.sto.stoapp.util.UnifiedStaticType;

public class TimingService extends Service {

	private TimingBroad timingBroad;
	// 订单定时器
	private AlarmManager orderTimer;
	// 上传定时器
	private AlarmManager uploadTimer;

	private PendingIntent orderSender;
	private PendingIntent uploadSender;

	private Handler broadHandler = new Handler() {

		public void handleMessage(Message msg) {
			try {

				if (msg.what == UnifiedStaticType.AUTO_DOWNLOAD_ORDER_TIMING) {
					autoOrderTiming();
				}

				if (msg.what == UnifiedStaticType.AUTO_UPLOAD_TIMING) {
					autoUploadTiming();
				}

			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("broadHandler", e.getMessage());
			}
		};

	};

	// 订单自动下载定时器
	private void autoOrderTiming() {
		int time = StoFilePreference.getInstance(TimingService.this)
				.getAutoDownloadOrderTime();

		// if (orderTimer != null) {
		// orderTimer.cancel();
		// orderTimer = null;
		// }
		// if (time >= 1) {
		// orderTime = time;
		// orderTimer = new Timer();
		// orderTimer.schedule(new TimerTask() {
		//
		// @Override
		// public void run() {
		// System.out.println("download order....");
		// Intent downIntent = new Intent(StoDownServer.UPDATE_ACTION);
		// downIntent.putExtra(StoDownServer.SERVER_DOWN_STATUS,
		// new int[] { MessageType.ORDER_DOWNLOAD_TYPE });
		// sendBroadcast(downIntent);
		// }
		// }, 0, orderTime * 60 * 1000);
		// }

		closeOrderTimer();
		if (time >= 5) {
			Intent intent = new Intent(StoDownServer.UPDATE_ACTION);
			intent.putExtra(StoDownServer.SERVER_DOWN_STATUS,
					new int[] { MessageType.ORDER_DOWNLOAD_TYPE });
			orderSender = PendingIntent.getBroadcast(TimingService.this, 0,
					intent, PendingIntent.FLAG_UPDATE_CURRENT);
			orderTimer = (AlarmManager) getSystemService(ALARM_SERVICE);
			// time * 60 秒一个周期，不停的发送广播
			orderTimer.setRepeating(AlarmManager.RTC_WAKEUP,
					System.currentTimeMillis() + (2 * 1000), time * 60 * 1000,
					orderSender);
		}

	}

	// 数据自动上传定时器
	private void autoUploadTiming() {
		int time = StoFilePreference.getInstance(TimingService.this)
				.getAutoUploadTime();

		closeUploadTimer();
		if (time >= 1) {
			Intent intent = new Intent(UnifiedStaticType.UP_ACTION);
			intent.putIntegerArrayListExtra(UnifiedStaticType.UPLOAD_TYPE,
					new ProcessUploadData().sendAllData());
			uploadSender = PendingIntent.getBroadcast(TimingService.this, 0,
					intent, PendingIntent.FLAG_UPDATE_CURRENT);
			uploadTimer = (AlarmManager) getSystemService(ALARM_SERVICE);
			// time * 60 秒一个周期，不停的发送广播
			uploadTimer.setRepeating(AlarmManager.RTC_WAKEUP,
					System.currentTimeMillis() + (2 * 1000), time * 60 * 1000,
					uploadSender);
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		timingBroad = new TimingBroad();
		IntentFilter filter = new IntentFilter(UnifiedStaticType.TIMING_ACTION);
		registerReceiver(timingBroad, filter);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		if (intent == null)
			return super.onStartCommand(intent, flags, startId);
		int status = intent.getIntExtra(UnifiedStaticType.TIMING_TYPE, 0);
		// 数据自动上传定时器
		if (status == UnifiedStaticType.AUTO_UPLOAD_TIMING) {
			autoUploadTiming();
		}
		return super.onStartCommand(intent, flags, startId);

	}

	class TimingBroad extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Message msg = broadHandler.obtainMessage();
			if (intent == null || msg == null)
				return;
			if (action.equals(UnifiedStaticType.TIMING_ACTION)) {

				msg.what = intent.getIntExtra(UnifiedStaticType.TIMING_TYPE, 0);
				broadHandler.sendMessage(msg);
			}
		}
	}

	/**
	 * 关闭订单自动下载
	 */
	public void closeOrderTimer() {
		if (orderTimer != null) {
			orderTimer.cancel(orderSender);
			orderTimer = null;
		}
	}

	/**
	 * 关闭数据自动上传
	 */
	public void closeUploadTimer() {
		if (uploadTimer != null) {
			uploadTimer.cancel(uploadSender);
			uploadTimer = null;
		}
	}

	@Override
	public void onDestroy() {
		unregisterReceiver(timingBroad);
		closeOrderTimer();
		closeUploadTimer();
		broadHandler
				.removeMessages(UnifiedStaticType.AUTO_DOWNLOAD_ORDER_TIMING);
		broadHandler.removeMessages(UnifiedStaticType.AUTO_UPLOAD_TIMING);
		super.onDestroy();
	}

}
